package com.example.prettyprint;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.nio.file.Paths;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class ExtractUzemniJednotkaHandler extends DefaultHandler
{
	private final String mElementName;
	private final PrintWriter mOutputFileStream;
	private int mDepthInElement = -1;
	
	public ExtractUzemniJednotkaHandler(String elementName, String outputDirectoryPath, String outputFileName) throws FileNotFoundException
	{
		this.mElementName = elementName;
		this.mOutputFileStream = new PrintWriter(new FileOutputStream(Paths.get(outputDirectoryPath, outputFileName).toFile()), true);
	}
	
	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		
		if(this.mDepthInElement >= 0)
		{
			++this.mDepthInElement;
			this.writeStartElement(qName, attributes);
		}
		else if(qName.equalsIgnoreCase(this.mElementName))
		{
			mDepthInElement = 0;
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		
		if(this.mDepthInElement >= 0)
		{
			if(--this.mDepthInElement >= 0)
				this.writeEndElement(qName);
		}
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {

		if(this.mDepthInElement >= 0)
			this.writeCharacters(ch, start, length);
	}

	private void writeStartElement(String qName, Attributes attributes) {
		
		//System.out.printf("<%s", qName);
		//this.mOutputFileStream.print(this.mDepthInElement);
		this.mOutputFileStream.printf("<%s", qName);

	  	for(int i = 0; i < attributes.getLength(); i++) {
	  		this.mOutputFileStream.printf(" %s = \"%s\"", attributes.getQName(i),attributes.getValue(i));
		}
	  	
	  	this.mOutputFileStream.print(">");
	  	this.mOutputFileStream.println();
	}
	
	private void writeEndElement(String qName) {
		
		//this.mOutputFileStream.print(this.mDepthInElement);
		//System.out.printf("</%s>", qName);
		this.mOutputFileStream.printf("</%s>", qName);
		this.mOutputFileStream.println();
	}
	
	private void writeCharacters(char[] ch, int start, int length) {

		//this.mOutputFileStream.printf("%d ", this.mDepthInElement);

		this.mOutputFileStream.print(new String(ch, start, length));
		this.mOutputFileStream.println();
	}
	
	@Override
	protected void finalize() throws Throwable {
		//this.mOutputFileStream.flush();
		this.mOutputFileStream.close();
		// TODO Auto-generated method stub
		super.finalize();
	}
}
